using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Forms;

using EveApiLib;

namespace EveSkillPocket
{
    public class EveApiLogic
    {
        private bool alert;
        private bool autoupdate;
        private EVESettings config;
        private Timer countdown;
        //private EventHandling eh = new EventHandling("EveSkillPocketWakeUp");
        private fCharacter form;
        private DateTime nextUpdate = DateTime.MaxValue;
        //private OutlookIntegration outlook;
        private EveSkillTraining skilltraining;

        public EveApiLogic(fCharacter form, EVESettings config)
        {
            this.form = form;
            this.config = config;
            //this.outlook = new OutlookIntegration(config);
            this.countdown = new Timer();
            this.countdown.Interval = 0x1388;
            this.countdown.Tick += new EventHandler(this.Tick);
            //this.eh.OnWakeUp += new EventHandling.WakeUpDelegate(this.OnWakeUp);
        }
    

        public void ClearRunAppAt()
        {
            Win32.SystemTime @null = Win32.SystemTime.Null;
            Win32.CeRunAppAtTime(fCharacter.GetDir() + @"\EveSkillPocket.exe", ref @null);
            //DebugLogger.Log("ClearRunAppAt");
            //this.eh.clearWakeup();
        }

        public void ClearWakeup()
        {
            //this.eh.clearWakeup();
        }

        public void DoUpdate()
        {
            this.ClearRunAppAt();
            this.alert = false;
            this.countdown.Enabled = false;
            Cursor.Current = Cursors.WaitCursor;
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            if (this.skilltraining != null)
            {
                this.skilltraining = null;
            }
            this.skilltraining = new EveSkillTraining();

            try
            {
                Label lblSkill = this.form.lblSkill;
                Label lblTimeLeft = this.form.lblTimeLeft;
                Label lblEndTime = this.form.lblEndTime;
                Label lblSkillPoints = this.form.lblSkillPoints;
                Label lblLastUpdate = this.form.lblLastUpdate;
                //EveAPI my_api = new EveAPI();
                //string xml = EveAPI.DoRequest(EveAPI.InitWebClient(EveAPI.GenerateURL(EveAPI.URL_SKILLTRAINING)), this.config.Config.GenerateURLEncodedBytes());
                
                string xml = EveAPI.DoRequest(EveAPI.InitWebClient(EveAPI.GenerateURL(EveAPI.URL_SKILLTRAINING)), this.config.Config.GenerateURLEncodedBytes());
                this.skilltraining.Parse(xml);
                if (this.skilltraining.SkillInTraining == 1)
                {
                    EveSkillTree skilltree = new EveSkillTree();
                    skilltree.LoadXmlFromFile(fCharacter.GetDir() + @"\Resources\SkillTree.xml");

                    //this.form.lblSkill.Text = string.Concat(new object[] { skilltree.GetSkillNameById((long)this.skilltraining.TrainingTypeID), "(", skilltree.GetSkillRankById((long)this.skilltraining.TrainingTypeID), ")" });
                    lblSkill.Text = string.Concat(new object[] { skilltree.GetSkillNameById((long)this.skilltraining.TrainingTypeID), " ", this.skilltraining.GetRomanToLevel(), " ", "(", skilltree.GetSkillRankById((long)this.skilltraining.TrainingTypeID), ")" });
                    lblTimeLeft.Text = this.skilltraining.GetTimeleftString();
                    lblEndTime.Text = EveAPI.EveToLocalTime(this.skilltraining.TrainingEnd).ToString();
                    //this.form.lblSkillpoints.Text = string.Concat(new object[] { "[", this.skilltraining.GetRomanToLevel(), "] ", this.skilltraining.TrainingStartSP, " to ", this.skilltraining.TrainingDestinationSP });
                    lblSkillPoints.Text = string.Concat(new object[] { this.skilltraining.TrainingStartSP, " to ", this.skilltraining.TrainingDestinationSP });
                    lblLastUpdate.Text = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
                    this.countdown.Enabled = true;
                    //this.UpdateTodayPlugin(skilltree);
                    skilltree = null;
                    if (this.skilltraining.GetTimeleftSeconds() > 0L)
                    {
                        this.SetupRunAppAt();
                    }
                }
                else
                {
                    lblSkill.Text = "(No Skill Training)";
                    lblSkillPoints.Text = "(No Skill Training)";
                    lblTimeLeft.Text = "(No Skill Training)";
                    lblEndTime.Text = "(No Skill Training)";
                    lblLastUpdate.Text = "Updated: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
                    this.countdown.Enabled = false;
                    //this.UpdateTodayPlugin(null);
                }
            }
            catch (WebException)
            {
                MessageBox.Show("Unable to connect to EVE API server.\nMake sure you have a working internet connection.");
            }
            catch (EveAPIException exception)
            {
                if (exception.Code == 1)
                {
                    MessageBox.Show("No Account/Character is activated.\nGo to Menu -> Character.. to select the character to check.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    MessageBox.Show("Error: " + exception.Message);
                    this.nextUpdate = DateTime.MaxValue;
                    this.AutoUpdate = false;
                    this.form.cbxSettingsAutoUpdate.Checked = false;
                    this.countdown.Enabled = false;
                }
            }
            Cursor.Current = Cursors.Default;
        }

        private void OnWakeUp()
        {
            //DebugLogger.Log("WakeUp Event: " + this.skilltraining.GetTimeleftSeconds());
            if ((this.skilltraining != null) && (this.skilltraining.GetTimeleftSeconds() < (this.config.Warning * 60)))
            {
                //DebugLogger.Log("Play Sound!");
                //this.eh.clearWakeup();
                Sound.PlaySound(fCharacter.GetDir() + @"\Resources\SkillTrained.wav");
            }
        }

        public void SetupRunAppAt()
        {
            if (this.skilltraining != null)
            {
                DateTime time = EveAPI.EveToLocalTime(this.skilltraining.TrainingEnd);
                if (this.config.Warning > 0)
                {
                    time = time.Subtract(new TimeSpan(0, this.config.Warning, 0));
                }
                Win32.SystemTime lpTime = new Win32.SystemTime(time);
                bool flag = Win32.CeRunAppAtTime(fCharacter.GetDir() + @"\EveSkillPocket.exe", ref lpTime);
                //DebugLogger.Log("CeRunAppAt: " + lpTime.ToString());
                if (!flag)
                {
                    MessageBox.Show("Unable to set Alarm.");
                    //DebugLogger.Log("Unable to set Alarm.");
                }
                //this.eh.setupWakeup();
            }
        }

        public void Tick(object sender, EventArgs e)
        {
            if (DateTime.Now > this.nextUpdate)
            {
                this.DoUpdate();
                if (this.AutoUpdate)
                {
                    this.nextUpdate = DateTime.Now.AddHours((double)this.config.AutoUpdateInterval);
                }
            }
            if (this.skilltraining != null)
            {
                this.form.lblTimeLeft.Text = this.skilltraining.GetTimeleftString();
                if ((this.skilltraining.GetTimeleftSeconds() < (this.config.Warning * 60)) && !this.alert)
                {
                    Sound.PlaySound(fCharacter.GetDir() + @"\Resources\SkillTrained.wav");
                    this.alert = true;
                }
                if (this.skilltraining.GetTimeleftTicks() <= 0L)
                {
                    this.countdown.Enabled = false;
                }
            }
            else
            {
                this.countdown.Enabled = false;
            }
        }

        public bool AutoUpdate
        {
            get
            {
                return this.autoupdate;
            }
            set
            {
                if (value)
                {
                    this.nextUpdate = DateTime.Now.AddHours((double)this.config.AutoUpdateInterval);
                }
                else
                {
                    this.nextUpdate = DateTime.MaxValue;
                }
                this.autoupdate = value;
            }
        }

        /* Disabled until I get the mainprogram running - Kazie
        public void UpdateTodayPlugin(EveSkillTree skilltree)
        {
            IntPtr hwnd = Win32.FindChildWindow(Win32.GetDesktopWindow(), "EVESkillPocketWindow");
            if (hwnd != IntPtr.Zero)
            {
                string e = "";
                if (this.skilltraining.SkillInTraining == 1)
                {
                    e = string.Concat(new object[] { "Character: ", this.config.Config.ActivatedChar.Name, "\r\nSkill: ", skilltree.GetSkillNameById((long)this.skilltraining.TrainingTypeID), " (", skilltree.GetSkillRankById((long)this.skilltraining.TrainingTypeID), ")\r\nCompletes: ", EveAPI.EveToLocalTime(this.skilltraining.TrainingEnd).ToString(), "\0" });
                }
                else
                {
                    e = "Character: " + this.config.Config.ActivatedChar.Name + "\r\nSkill: No Skill in Training!\0";
                }
                Win32.COPYDATASTRUCT lParam = new Win32.COPYDATASTRUCT();
                lParam.dwData = 0x4711;
                lParam.cbData = (e.Length + 5) * 2;
                lParam.lpData = Win32.VarPtr(e);
                Win32.SendMessage(hwnd, 0x4a, 13, lParam);
            }
        }

        public OutlookIntegration Outlook
        {
            get
            {
                return this.outlook;
            }
        }
        */

        public EveSkillTraining Training
        {
            get
            {
                return this.skilltraining;
            }
        }
    }
}